package test;

import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import com.sun.org.apache.xml.internal.security.utils.Base64;

public class change {
private static final String KEY_ALGORITHM = "RSA";     
private static final String PUBLIC_KEY ="publicKey";   
private static final String PRIVATE_KEY ="privateKey";    
public static final String PUBLIC ="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDC+b50e4/a7YkYvcaYkED5XVyVwn0zGV8RVdfm"
+"F52W0KH1YuG4ec8c1RNryW+An3ky1bWjkkiT/u8UsQfghs/YPgSqwmhH/YsgE/xDD3H5ON8+bWLO"
+"uongraZ1wWfc8tsWRR9sHdb43dWJYAVvb59gWWlcVQFt9vfYaX61bWhXywIDAQAB"; 
public static final String PRIVATE ="MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAML5vnR7j9rtiRi9xpiQQPldXJXC"
+"fTMZXxFV1+YXnZbQofVi4bh5zxzVE2vJb4CfeTLVtaOSSJP+7xSxB+CGz9g+BKrCaEf9iyAT/EMP"
+"cfk43z5tYs66ieCtpnXBZ9zy2xZFH2wd1vjd1YlgBW9vn2BZaVxVAW3299hpfrVtaFfLAgMBAAEC"
+"gYEAh5l/jq1cqArpfS6HDxXMSmFXAcSopEAx8PF93MVx0TC6YtnpWA5HL6s0/ZKznIXMmcEtuVwE"
+"ZAE6L27Lpqi7pVaShN3tNh+bAsFJKS67w1BRbYRY0BHuITnDwGilS+Zy8gzyOAHklBnvobYX3pjB"
+"z53qkswPy1SI2b4kXcuy3aECQQDrj6KK3fB+IICB1tne1xcXOr9CBXhDv22R6PYsw68nKUeb6hIM"
+"M6SIK88ZlKckUKjsnHomi7CHiIMFr5ZhxWG7AkEA0+ScBA7ZTfM9cPPO0U7fkd023i3brMVjYHWw"
+"Wmd7jEoVElD8Yg2ycZ/BJsVR5duXK5cckX0m1zCSZc1nJro5MQJBANgEzIaUqSrBG5f2M65LiX1f"
+"/mzJH1Thg9W+0aKTgVhkXqr4qLxPz56grjdDP1PqND9n8AzRJX3lDmJ0d3AJ1mkCQGfjeirzLM/v"
+"JnyuzQQKa8sUbsZYLZBz5tlwWlq4yfZqjBJC6rsYhBj5frYHoLPWCjQxDqy2c8il4+FN5/kw7MEC"
+"QCiHU8hfB3E5PwV484TFjeuJMstHWB1WDs0/ryro0MFmlogohfCYqOkD6RVtXf2z12d6DOS57/IQ"
+"70+Y356xN0U="; 
public static void main(String[] args) throws Exception{   
//    Map<String,String> keyMap = genKey();   
    RSAPublicKey publicKey = getPublicKey(PUBLIC);   
    RSAPrivateKey privateKey = getPrivateKey(PRIVATE);   
//    String pub1= keyMap.get(PUBLIC_KEY);
//    String private1= keyMap.get(PRIVATE_KEY);
//    System.out.println(pub1);  
//    System.out.println(private1);  
    String info ="明文123456";   
    //加密   
    byte[] bytes = encrypt(publicKey,info.getBytes("utf-8"));   
    System.out.println(new String(bytes,"utf-8")); 
    //解密   
    bytes = decrypt(privateKey,bytes);   
    System.out.println(publicKey.toString());   
    System.out.println(privateKey.toString());   
    System.out.println(new String(bytes,"utf-8"));   
        
}   
  
/**
 * 产生密钥对并存放在Map<String,String>中
 * @return
 * @throws NoSuchAlgorithmException
 */
public static Map<String,String> genKey() throws NoSuchAlgorithmException{   
    Map<String,String> keyMap = new HashMap<String,String>();   
    KeyPairGenerator keygen = KeyPairGenerator.getInstance(KEY_ALGORITHM);   
    SecureRandom random = new SecureRandom();   
    // random.setSeed(keyInfo.getBytes());   
    // 初始加密，512位已被破解，用1024位,最好用2048位   
    keygen.initialize(1024, random);   
    // 取得密钥对   
    KeyPair kp = keygen.generateKeyPair();   
    RSAPrivateKey privateKey = (RSAPrivateKey)kp.getPrivate();   
    String privateKeyString = Base64.encode(privateKey.getEncoded());   
    RSAPublicKey publicKey = (RSAPublicKey)kp.getPublic();    
    String publicKeyString = Base64.encode(publicKey.getEncoded());   
    keyMap.put(PUBLIC_KEY, publicKeyString);   
    keyMap.put(PRIVATE_KEY, privateKeyString);   
    return keyMap;   
}   
  
/**
 * 将字符串密钥转化成RSAPublicKey类型的公钥
 * @param publicKey
 * @return
 * @throws Exception
 */
public static RSAPublicKey getPublicKey(String publicKey) throws Exception{   
    byte[] keyBytes = Base64.decode(publicKey);   
    X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);   
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);   
    return (RSAPublicKey) keyFactory.generatePublic(spec);   
}   
  
/**
 * 将字符串密钥转化成RSAPrivateKey类型的私钥
 * @param privateKey
 * @return
 * @throws Exception
 */
public static RSAPrivateKey getPrivateKey(String privateKey) throws Exception{   
    byte[] keyBytes = Base64.decode(privateKey);   
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);   
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);   
    return (RSAPrivateKey) keyFactory.generatePrivate(spec);   
}  


/**
 * 加密
 * @param publicKey
 * @param srcBytes
 * @return
 * @throws NoSuchAlgorithmException
 * @throws NoSuchPaddingException
 * @throws InvalidKeyException
 * @throws IllegalBlockSizeException
 * @throws BadPaddingException
 */
public static byte[] encrypt(RSAPublicKey publicKey,byte[] srcBytes) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{  
    if(publicKey!=null){  
    //Cipher负责完成加密或解密工作，基于RSA  
    Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);  
    //根据公钥，对Cipher对象进行初始化  
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);  
    byte[] resultBytes = cipher.doFinal(srcBytes);  
    return resultBytes;  
    }  
    return null;  
 }  
        
/**
 * 解密
 * @param privateKey
 * @param srcBytes
 * @return
 * @throws NoSuchAlgorithmException
 * @throws NoSuchPaddingException
 * @throws InvalidKeyException
 * @throws IllegalBlockSizeException
 * @throws BadPaddingException
 */
public static byte[] decrypt(RSAPrivateKey privateKey,byte[] srcBytes) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{  
    if(privateKey!=null){  
    //Cipher负责完成加密或解密工作，基于RSA  
    Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);  
    //根据公钥，对Cipher对象进行初始化  
    cipher.init(Cipher.DECRYPT_MODE, privateKey);  
    byte[] resultBytes = cipher.doFinal(srcBytes);  
    return resultBytes;  
    }  
    return null;  
 }  
}

